<?php

/**
 * Passport Class
 * @author ReGeDa
 * @events :new :validate
 */
class Passport_Handler extends DB_Event_Handler {

	/**
	 * Create a new passport
	 */
	public function on_new() {

		$AQ = &platcode()->plugins->import('ActiveQuery');
		/* @var $AQ ActiveQuery */

		// prepare SQL
		$stmt = $this->db->prepare(
			$AQ->set(array('email','username','secret'))->call('create_account')
		);
		/* @var $stmt PDOStatement */

		// set ID result
		$stmt->bindColumn(1, $id);
		// set HASH for e-mail accepting
		$stmt->bindColumn(2, $secret_hash);

		////////////////////////////////////////// Database query

		try {
			// SQL query
			$AQ->query($stmt);
			// fetch a row
			$stmt->fetch();
			// view result
			platcode()->raw['id'] = $id;

			// @todo send message to EMAIL post with [$id, $secret_hash]

			////////////////////////////
		} catch (PDOException $e) {
			// error output
			platcode()->raw = array(
				'code' => $e->getCode(),
				'err' => $this->normalize_error($e)
			);
		}
	}

	/**
	 * Validate a user account
	 * @param string $column
	 */
	public function on_validate($column) {

		$AQ = &platcode()->plugins->import('ActiveQuery');
		/* @var $AQ ActiveQuery */

		// prepare SQL
		$stmt = $this->db->prepare(
			$AQ
				->set('column', $column) // column name
				->set(array($column, 'secret')) // values from POST
				->set(array(
					'timeout' => config('untrust_email_life'),
					'salt' => config('password_salt')
				))
				->call('validate_user')
		);
		/* @var $stmt PDOStatement */

		////////////////////////////////////////// Database query

		try {

			// SQL query
			$AQ->query($stmt);

			// fetch a row
			// [user_id, name, hash]
			$data = $stmt->fetch(PDO::FETCH_ASSOC);

			// shift user ID
			$id = array_shift($data);

			// set session
			platcode()->plugins->import('Session')->allocate_client(
				$id,
				$data, // [name, hash]
				platcode()->plugins->import('Input')->post('remember') ? 63072000 : 0 // time to life
			);

			// result
			platcode()->raw = array(
				'id' => $id,
				'name' => $data['name']
			);

		} catch (PDOException $e) {
			// error output
			platcode()->raw['err'] = lang('access_denied');
		}

	}

}

// end of file